<template>
  <div class="page-user-login">
    <van-nav-bar
      left-arrow
      @click-left="$router.back()"
      title="登录"
    ></van-nav-bar>
    <van-form @submit="onSubmit">
      <van-field
        v-model="formData.mobile"
        name="mobile"
        label="手机号"
        placeholder="手机号"
        :rules="[{ required: true, message: '请填写手机号' }, {pattern,message:'请填写正确的手机号'}]"
      />
      <van-field
        v-model="formData.code"
        name="code"
        label="验证码"
        placeholder="验证码"
        :rules="[{ required: true, message: '请填写验证码' }, {validator,message:'验证码错误'}]"
      >
        <template #button>
          <van-button
            size="small"
            type="primary"
            native-type="button"
          >发送验证码</van-button>
        </template>
      </van-field>
      <div style="margin: 16px;">
        <van-button
          round
          block
          type="info"
          native-type="submit"
        >登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  data () {
    return {
      pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
      formData: {
        mobile: '13611111111',
        code: '246810'
      }
    }
  },
  methods: {
    ...mapMutations(['setToken']),
    async onSubmit (values) {
      // console.log('submit', values)
      try {
        const { data } = await loginAPI(values)
        // console.log(data)
        this.setToken(data)
        this.$router.replace(this.$route.query.redirectUrl || '/user')
        this.$toast.success('登陆成功')
      } catch (error) {
        this.$toast.fail('手机号或验证码错误')
      }
    },
    // 函数形式的验证规则
    validator (val) {
      return /\d{6}/.test(val)
    }
  }
}
</script>

<style scoped lang='less'></style>
